import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { adminAPI } from '../api'

export const useAdminStore = defineStore('admin', () => {
  // 状态
  const statistics = ref(null)
  const students = ref([])
  const majors = ref([])
  const classes = ref([])
  const dormitories = ref({
    buildings: [],
    rooms: []
  })
  const registrations = ref([])
  const finance = ref({
    paymentItems: [],
    paymentRecords: [],
    statistics: null
  })
  const notices = ref([])
  const isLoading = ref(false)
  const pagination = ref({
    current: 1,
    pageSize: 10,
    total: 0
  })

  // 计算属性
  const totalStudents = computed(() => statistics.value?.totalStudents || 0)
  const registeredStudents = computed(() => statistics.value?.registeredStudents || 0)
  const registrationRate = computed(() => {
    if (totalStudents.value === 0) return 0
    return Math.round((registeredStudents.value / totalStudents.value) * 100)
  })

  const totalPaymentAmount = computed(() => finance.value.statistics?.totalAmount || 0)
  const paidAmount = computed(() => finance.value.statistics?.paidAmount || 0)
  const paymentRate = computed(() => {
    if (totalPaymentAmount.value === 0) return 0
    return Math.round((paidAmount.value / totalPaymentAmount.value) * 100)
  })

  // 获取统计数据
  const getStatistics = async () => {
    try {
      isLoading.value = true
      const response = await adminAPI.getStatistics()
      // 适配新的响应格式
      if (response.data && response.data.code === 200) {
        statistics.value = response.data.data
        return response.data
      } else {
        throw new Error(response.data?.message || '获取统计数据失败')
      }
    } catch (error) {
      console.error('获取统计数据失败:', error)
      throw error
    } finally {
      isLoading.value = false
    }
  }

  // 学生管理相关方法
  const getStudents = async (params = {}) => {
    try {
      isLoading.value = true
      const response = await adminAPI.students.getList(params)
      console.log('API响应:', response)
      
      // 响应拦截器已经返回了response.data，所以这里直接使用response
      if (response && response.code === 1) {
        const data = response.data
        students.value = data.rows || []
        pagination.value = {
          current: params.page || 1,
          pageSize: params.pageSize || 10,
          total: data.total || 0
        }
        console.log('获取学生列表成功:', data)
        return response
      } else {
        console.error('获取学生列表失败:', response?.msg || '未知错误')
        throw new Error(response?.msg || '获取学生列表失败')
      }
    } catch (error) {
      console.error('获取学生列表失败:', error)
      throw error
    } finally {
      isLoading.value = false
    }
  }

  const createStudent = async (data) => {
    try {
      const response = await adminAPI.students.create(data)
      // 适配新的响应格式
      if (response.data && response.data.code === 200) {
        // 刷新学生列表
        await getStudents()
        return { success: true, message: response.data.message || '学生创建成功' }
      } else {
        return { success: false, message: response.data?.message || '学生创建失败' }
      }
    } catch (error) {
      return { success: false, message: error.response?.data?.message || error.message || '学生创建失败' }
    }
  }

  const updateStudent = async (id, data) => {
    try {
      await adminAPI.students.update(id, data)
      // 更新本地状态
      const index = students.value.findIndex(s => s.id === id)
      if (index !== -1) {
        students.value[index] = { ...students.value[index], ...data }
      }
      return { success: true, message: '学生信息更新成功' }
    } catch (error) {
      return { success: false, message: error.message || '学生信息更新失败' }
    }
  }

  const deleteStudent = async (id) => {
    try {
      await adminAPI.students.delete(id)
      // 从本地状态中移除
      students.value = students.value.filter(s => s.id !== id)
      return { success: true, message: '学生删除成功' }
    } catch (error) {
      return { success: false, message: error.message || '学生删除失败' }
    }
  }

  const batchImportStudents = async (file) => {
    try {
      const response = await adminAPI.students.batchImport(file)
      // 刷新学生列表
      await getStudents()
      return { success: true, message: '学生批量导入成功', data: response.data }
    } catch (error) {
      return { success: false, message: error.message || '学生批量导入失败' }
    }
  }

  // 专业管理相关方法
  const getMajors = async () => {
    try {
      const response = await adminAPI.majors.getList()
      majors.value = response.data
      return response
    } catch (error) {
      console.error('获取专业列表失败:', error)
      throw error
    }
  }

  const createMajor = async (data) => {
    try {
      const response = await adminAPI.majors.create(data)
      majors.value.push(response.data)
      return { success: true, message: '专业创建成功' }
    } catch (error) {
      return { success: false, message: error.message || '专业创建失败' }
    }
  }

  const updateMajor = async (id, data) => {
    try {
      await adminAPI.majors.update(id, data)
      const index = majors.value.findIndex(m => m.id === id)
      if (index !== -1) {
        majors.value[index] = { ...majors.value[index], ...data }
      }
      return { success: true, message: '专业更新成功' }
    } catch (error) {
      return { success: false, message: error.message || '专业更新失败' }
    }
  }

  const deleteMajor = async (id) => {
    try {
      await adminAPI.majors.delete(id)
      majors.value = majors.value.filter(m => m.id !== id)
      return { success: true, message: '专业删除成功' }
    } catch (error) {
      return { success: false, message: error.message || '专业删除失败' }
    }
  }

  // 班级管理相关方法
  const getClasses = async (params = {}) => {
    try {
      const response = await adminAPI.classes.getList(params)
      classes.value = response.data
      return response
    } catch (error) {
      console.error('获取班级列表失败:', error)
      throw error
    }
  }

  const createClass = async (data) => {
    try {
      const response = await adminAPI.classes.create(data)
      classes.value.push(response.data)
      return { success: true, message: '班级创建成功' }
    } catch (error) {
      return { success: false, message: error.message || '班级创建失败' }
    }
  }

  // 宿舍管理相关方法
  const getDormitoryBuildings = async () => {
    try {
      const response = await adminAPI.dormitories.getBuildings()
      dormitories.value.buildings = response.data
      return response
    } catch (error) {
      console.error('获取楼宇列表失败:', error)
      throw error
    }
  }

  const getDormitoryRooms = async (params = {}) => {
    try {
      const response = await adminAPI.dormitories.getRooms(params)
      dormitories.value.rooms = response.data
      return response
    } catch (error) {
      console.error('获取宿舍列表失败:', error)
      throw error
    }
  }

  const assignDormitory = async (data) => {
    try {
      await adminAPI.dormitories.assignRoom(data)
      // 刷新宿舍信息
      await getDormitoryRooms()
      return { success: true, message: '宿舍分配成功' }
    } catch (error) {
      return { success: false, message: error.message || '宿舍分配失败' }
    }
  }

  // 报到管理相关方法
  const getRegistrations = async (params = {}) => {
    try {
      const response = await adminAPI.registration.getList(params)
      registrations.value = response.data
      return response
    } catch (error) {
      console.error('获取报到列表失败:', error)
      throw error
    }
  }

  const confirmRegistration = async (studentId) => {
    try {
      await adminAPI.registration.confirm(studentId)
      // 更新本地状态
      const registration = registrations.value.find(r => r.studentId === studentId)
      if (registration) {
        registration.status = '已报到'
        registration.registrationTime = new Date().toISOString()
      }
      return { success: true, message: '报到确认成功' }
    } catch (error) {
      return { success: false, message: error.message || '报到确认失败' }
    }
  }

  // 财务管理相关方法
  const getPaymentItems = async () => {
    try {
      const response = await adminAPI.finance.getPaymentItems()
      finance.value.paymentItems = response.data
      return response
    } catch (error) {
      console.error('获取缴费项目失败:', error)
      throw error
    }
  }

  const getPaymentRecords = async (params = {}) => {
    try {
      const response = await adminAPI.finance.getPaymentRecords(params)
      finance.value.paymentRecords = response.data
      return response
    } catch (error) {
      console.error('获取缴费记录失败:', error)
      throw error
    }
  }

  const getFinanceStatistics = async () => {
    try {
      const response = await adminAPI.finance.getStatistics()
      finance.value.statistics = response.data
      return response
    } catch (error) {
      console.error('获取财务统计失败:', error)
      throw error
    }
  }

  // 通知公告相关方法
  const getNotices = async (params = {}) => {
    try {
      const response = await adminAPI.notices.getList(params)
      notices.value = response.data
      return response
    } catch (error) {
      console.error('获取通知列表失败:', error)
      throw error
    }
  }

  const createNotice = async (data) => {
    try {
      const response = await adminAPI.notices.create(data)
      notices.value.unshift(response.data)
      return { success: true, message: '通知创建成功' }
    } catch (error) {
      return { success: false, message: error.message || '通知创建失败' }
    }
  }

  const publishNotice = async (id) => {
    try {
      await adminAPI.notices.publish(id)
      const notice = notices.value.find(n => n.id === id)
      if (notice) {
        notice.status = '已发布'
        notice.publishTime = new Date().toISOString()
      }
      return { success: true, message: '通知发布成功' }
    } catch (error) {
      return { success: false, message: error.message || '通知发布失败' }
    }
  }

  // 初始化管理员数据
  const initAdminData = async () => {
    try {
      await Promise.all([
        getStatistics(),
        getMajors(),
        getClasses()
      ])
    } catch (error) {
      console.error('初始化管理员数据失败:', error)
    }
  }

  // 清除管理员数据
  const clearAdminData = () => {
    statistics.value = null
    students.value = []
    majors.value = []
    classes.value = []
    dormitories.value = { buildings: [], rooms: [] }
    registrations.value = []
    finance.value = { paymentItems: [], paymentRecords: [], statistics: null }
    notices.value = []
  }

  return {
    // 状态
    statistics,
    students,
    majors,
    classes,
    dormitories,
    registrations,
    finance,
    notices,
    isLoading,
    pagination,
    
    // 计算属性
    totalStudents,
    registeredStudents,
    registrationRate,
    totalPaymentAmount,
    paidAmount,
    paymentRate,
    
    // 方法
    getStatistics,
    getStudents,
    createStudent,
    updateStudent,
    deleteStudent,
    batchImportStudents,
    getMajors,
    createMajor,
    updateMajor,
    deleteMajor,
    getClasses,
    createClass,
    getDormitoryBuildings,
    getDormitoryRooms,
    assignDormitory,
    getRegistrations,
    confirmRegistration,
    getPaymentItems,
    getPaymentRecords,
    getFinanceStatistics,
    getNotices,
    createNotice,
    publishNotice,
    initAdminData,
    clearAdminData
  }
})